<template>
  <div class="ai-chat-container">
    <el-card class="chat-card">
      <template #header>
        <div class="chat-header">
          <el-icon :size="24" color="#409EFF"><ChatDotRound /></el-icon>
          <span class="title">AI智能客服</span>
          <el-button size="small" @click="clearHistory" :disabled="messages.length === 0">
            <el-icon><Delete /></el-icon>
            清空对话
          </el-button>
        </div>
      </template>

      <!-- 聊天消息区域 -->
      <div class="messages-container" ref="messagesContainer">
        <div v-if="messages.length === 0" class="welcome-message">
          <el-icon :size="60" color="#409EFF"><ChatDotRound /></el-icon>
          <h3>欢迎使用AI智能客服</h3>
          <p>我可以帮您解答关于WMS系统的问题</p>
        </div>

        <div
          v-for="(message, index) in messages"
          :key="index"
          :class="['message-item', message.role]"
        >
          <div class="message-avatar">
            <el-avatar v-if="message.role === 'user'" :size="36">
              <el-icon><User /></el-icon>
            </el-avatar>
            <el-avatar v-else :size="36" style="background-color: #409EFF;">
              <el-icon><Service /></el-icon>
            </el-avatar>
          </div>
          <div class="message-content">
            <div class="message-text">{{ message.content }}</div>
            <div class="message-time">{{ message.time }}</div>
          </div>
        </div>

        <!-- 加载中 -->
        <div v-if="isLoading" class="message-item assistant">
          <div class="message-avatar">
            <el-avatar :size="36" style="background-color: #409EFF;">
              <el-icon><Service /></el-icon>
            </el-avatar>
          </div>
          <div class="message-content">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-container">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          placeholder="请输入您的问题..."
          @keydown.enter.exact="handleSend"
          @keydown.enter.shift.exact.prevent="inputMessage += '\n'"
          :disabled="isLoading"
        />
        <div class="input-actions">
          <span class="input-hint">按 Enter 发送，Shift + Enter 换行</span>
          <el-button
            type="primary"
            @click="handleSend"
            :loading="isLoading"
            :disabled="!inputMessage.trim()"
          >
            <el-icon><Promotion /></el-icon>
            发送
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, nextTick, getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';
import {
  ChatDotRound,
  User,
  Service,
  Delete,
  Promotion
} from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance();

// 消息列表
const messages = ref([]);

// 输入框
const inputMessage = ref('');

// 加载状态
const isLoading = ref(false);

// 消息容器引用
const messagesContainer = ref(null);

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
};

// 格式化时间
const formatTime = () => {
  const now = new Date();
  return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
};

// 发送消息（流式响应）
const handleSend = async () => {
  if (!inputMessage.value.trim() || isLoading.value) {
    return;
  }

  const userMessage = inputMessage.value.trim();
  inputMessage.value = '';

  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: userMessage,
    time: formatTime()
  });

  scrollToBottom();
  isLoading.value = true;

  try {
    // 构建历史消息
    const history = messages.value.map(msg => ({
      role: msg.role,
      content: msg.content
    }));

    // 调用流式API
    const response = await fetch(proxy.http.ipAddress + 'api/AIChat/stream', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        message: userMessage,
        history: history.slice(0, -1) // 排除刚添加的用户消息
      })
    });

    if (!response.ok) {
      throw new Error('请求失败');
    }

    // 读取流式响应
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    
    // 创建AI消息
    const aiMessage = {
      role: 'assistant',
      content: '',
      time: formatTime()
    };
    messages.value.push(aiMessage);

    let buffer = '';

    while (true) {
      const { done, value } = await reader.read();
      
      if (done) {
        break;
      }

      buffer += decoder.decode(value, { stream: true });
      
      // 处理每一行数据
      const lines = buffer.split('\n');
      buffer = lines.pop(); // 保留最后一个不完整的行

      for (const line of lines) {
        if (line.startsWith('data:')) {
          const dataStr = line.substring(5).trim();
          
          if (dataStr === '[DONE]') {
            console.log('✅ 流式响应完成');
            continue;
          }

          try {
            const data = JSON.parse(dataStr);
            
            if (data.choices && data.choices.length > 0) {
              const delta = data.choices[0].delta;
              
              if (delta && delta.content) {
                aiMessage.content += delta.content;
                scrollToBottom();
              }
            }
          } catch (e) {
            console.warn('解析数据失败:', dataStr);
          }
        }
      }
    }

    isLoading.value = false;
    scrollToBottom();

  } catch (error) {
    console.error('发送消息失败:', error);
    ElMessage.error('发送消息失败: ' + error.message);
    isLoading.value = false;
    
    // 移除失败的AI消息
    if (messages.value[messages.value.length - 1].role === 'assistant' && 
        !messages.value[messages.value.length - 1].content) {
      messages.value.pop();
    }
  }
};

// 清空对话历史
const clearHistory = () => {
  messages.value = [];
  ElMessage.success('对话历史已清空');
};
</script>

<style scoped lang="less">
.ai-chat-container {
  padding: 20px;
  height: calc(100vh - 100px);
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f7fa;

  .chat-card {
    width: 100%;
    max-width: 900px;
    height: 100%;
    display: flex;
    flex-direction: column;

    :deep(.el-card__header) {
      padding: 15px 20px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;

      .chat-header {
        display: flex;
        align-items: center;
        gap: 10px;

        .title {
          flex: 1;
          font-size: 18px;
          font-weight: bold;
        }

        .el-button {
          color: white;
          border-color: rgba(255, 255, 255, 0.3);

          &:hover {
            background: rgba(255, 255, 255, 0.2);
            border-color: rgba(255, 255, 255, 0.5);
          }
        }
      }
    }

    :deep(.el-card__body) {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      padding: 0;
    }
  }

  .messages-container {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background: #fafafa;

    .welcome-message {
      text-align: center;
      padding: 60px 20px;
      color: #909399;

      h3 {
        margin: 20px 0 10px;
        font-size: 20px;
        color: #303133;
      }

      p {
        margin: 0;
        font-size: 14px;
      }
    }

    .message-item {
      display: flex;
      margin-bottom: 20px;
      animation: fadeIn 0.3s;

      &.user {
        flex-direction: row-reverse;

        .message-content {
          align-items: flex-end;

          .message-text {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
          }

          .message-time {
            text-align: right;
          }
        }
      }

      &.assistant {
        .message-text {
          background: white;
          color: #303133;
        }
      }

      .message-avatar {
        flex-shrink: 0;
        margin: 0 10px;
      }

      .message-content {
        display: flex;
        flex-direction: column;
        max-width: 70%;

        .message-text {
          padding: 12px 16px;
          border-radius: 12px;
          line-height: 1.6;
          word-break: break-word;
          white-space: pre-wrap;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .message-time {
          margin-top: 5px;
          font-size: 12px;
          color: #909399;
          padding: 0 5px;
        }

        .typing-indicator {
          display: flex;
          align-items: center;
          gap: 4px;
          padding: 12px 16px;
          background: white;
          border-radius: 12px;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

          span {
            width: 8px;
            height: 8px;
            background: #409EFF;
            border-radius: 50%;
            animation: typing 1.4s infinite;

            &:nth-child(2) {
              animation-delay: 0.2s;
            }

            &:nth-child(3) {
              animation-delay: 0.4s;
            }
          }
        }
      }
    }
  }

  .input-container {
    border-top: 1px solid #e4e7ed;
    padding: 15px 20px;
    background: white;

    .input-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 10px;

      .input-hint {
        font-size: 12px;
        color: #909399;
      }
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.7;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}

::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;

  &:hover {
    background: #c0c4cc;
  }
}
</style>

